import { App, VNode, h } from 'vue'
import $store from '@/store'

// 校验权限是否存在
const isAuthorization = (value: string | string[]) => {
  let list: string | string[] = []
  if (Object.prototype.toString.call(value) === '[object Array]') {
    list = value || []
  } else if (typeof value === 'string') {
    list = value.split(',')
  }
  const authorizationList = $store.getters.authorizationList || []
  const len = list.length
  let index = 0
  for (; index < len; index++) {
    if (authorizationList.includes(list[index])) {
      return true
    }
  }
  return false
}

// directive v-auth
const setupAuthority = (app: App) => {
  app.directive('auth', (el, { value }) => {
    if (!isAuthorization(value)) {
      // 权限不存在，删除元素
      el.remove()
    }
  })
}

// hooks
const useAuthority = () => {
  return {
    is: (value: string | string[], el?: VNode, placeholder?: VNode | boolean | string | number) => {
      const is = isAuthorization(value)
      if (el) {
        if (is) {
          return el
        } else {
          if (placeholder) {
            return placeholder
          } else {
            return null
          }
        }
      } else {
        return is
      }
    }
  }
}

export { setupAuthority, useAuthority }
